package com.psct.music;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.psct.R;

public class Main extends Activity {
	private Button m_playBtn, m_pauseBtn, m_restBtn, m_stopBtn;
	private MediaPlayer m_player;
	private boolean m_bIsReleased = false;
	private boolean m_bIsPaused = false;
	private boolean m_bIsStreaming = true;

	private String m_strFileURL = "http://www.android-study.com/upload/media/android.mp3";
	// private String m_strFileURL =
	// "http://www.xingyang.org/music/%B9%C5%F3%DD/Track02.mp3";

	private String m_strTempFilePath = "";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.test);
		m_playBtn = (Button) findViewById(R.id.playBtn);
		m_pauseBtn = (Button) findViewById(R.id.pauseBtn);
		m_restBtn = (Button) findViewById(R.id.resetBtn);
		m_stopBtn = (Button) findViewById(R.id.stopBtn);
		m_playBtn.setOnClickListener(new Button.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Play(m_strFileURL);
				LogI("MediaPlayer start playing");
			}

		});
		m_pauseBtn.setOnClickListener(new Button.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub

				if (m_player != null) {
					if (!m_bIsReleased) {
						if (!m_bIsPaused) {
							m_player.pause();
							m_bIsPaused = true;
						} else {
							m_player.start();
							m_bIsPaused = false;
						}
					}
				}
			}

		});
		m_restBtn.setOnClickListener(new Button.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub

				if (m_player != null) {
					if (!m_bIsReleased) {
						m_player.seekTo(0);
						LogI("MediaPlayer reset");
					}
				}
			}

		});
		m_stopBtn.setOnClickListener(new Button.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub

				if (m_player != null) {
					if (!m_bIsReleased) {
						m_player.seekTo(0);
						m_player.pause();
						LogI("MediaPlayer stop");
					}
				}
			}

		});
	}

	private void Play(final String strURL) {
		if (m_player != null) {
			m_player.start();
			return;
		}
		m_player = new MediaPlayer();
		m_player.setAudioStreamType(AudioManager.STREAM_RING);
		// 监听错误事件
		m_player.setOnErrorListener(new MediaPlayer.OnErrorListener() {

			public boolean onError(MediaPlayer mp, int what, int extra) {
				LogI("Error on Listener, what: " + what + "extra: " + extra);
				return false;
			}

		});
		// 监听缓冲事件
		m_player.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {

			public void onBufferingUpdate(MediaPlayer mp, int percent) {
				// TODO Auto-generated method stub
				LogI("MediaPlayer Update buffer: " + Integer.toString(percent) + "%");
			}

		});
		// 监听播放完毕事件
		m_player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

			public void onCompletion(MediaPlayer mp) {
				// TODO Auto-generated method stub
				LogI("MediaPlayer Listener Completed");
			}

		});
		// 监听准备事件
		m_player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

			public void onPrepared(MediaPlayer mp) {
				// TODO Auto-generated method stub
				LogI("MediaPlayer Prepared Listener");
			}

		});
		Runnable r = new Runnable() {

			public void run() {
				// TODO Auto-generated method stub
				try {
					if (m_bIsStreaming) {
						m_player.setDataSource(Main.this, Uri.parse(m_strFileURL));
					} else {
						SetDataSource(strURL);
					}
					m_player.prepare();
					LogI("Duration: " + m_player.getDuration());
					m_player.start();
					m_bIsReleased = false;
				} catch (Exception e) {
					LogE(e.getMessage(), e);
				}
			}

		};
		new Thread(r).start();
	}

	private void SetDataSource(String strURL) throws Exception {
		if (!m_bIsReleased) {
			URL url = new URL(strURL);
			URLConnection conn = url.openConnection();
			InputStream in = conn.getInputStream();
			if (in == null)
				throw new RuntimeException("stream is null");
			File file = File.createTempFile("player_mp3_cache", ".mp3", Main.this.getCacheDir());
			if (!file.exists())
				file.createNewFile();
			m_strTempFilePath = file.getAbsolutePath();
			FileOutputStream fos = new FileOutputStream(file);
			byte buffer[] = new byte[128];
			do {
				int nNumRead = in.read(buffer);
				if (nNumRead <= 0)
					break;
				fos.write(buffer);
			} while (true);
			m_player.setDataSource(m_strTempFilePath);
			in.close();
			fos.close();
		}
	}

	private void DeleteFile(String strPath) {
		File file = new File(strPath);
		if (file.exists())
			file.delete();
	}

	private void LogI(String str) {
		Log.i("Play_Web_Mp3", str);
	}

	private void LogE(String str, Throwable tr) {
		Log.e("Play_Web_Mp3", str, tr);
	}

	@Override
	protected void onPause() {
		// 删除临时文件
		DeleteFile(m_strTempFilePath);
		super.onPause();
	}
}
